package com.wx.network.client;

import com.wx.cache.LouckCache;
import com.wx.cache.ResponseCache;
import com.wx.content.DataType;
import com.wx.network.codec.RpcProtocol;
import com.wx.network.handler.PangHeartBeatHandler;
import com.wx.network.heartbeat.HeatBeatPackage;
import com.wx.network.mesg.Response;
import com.wx.util.SerializationUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class RpcClientHandler  extends SimpleChannelInboundHandler<RpcProtocol> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol rpcProtocol) throws Exception {
        //获得服务器响应的数据
        byte[] data = rpcProtocol.getData();
        Response response = SerializationUtil.unSerialzationObj(data, Response.class);
        String requestId = response.getRequestId();
        log.info("================================");
        log.info(response.getDataType().name());
        log.info("================================");
        if(response.getDataType().equals(DataType.PANG)){
                log.info("客户端收到服务器心跳回复【{}】",(HeatBeatPackage)response.getResult());
        }else if (response.getDataType().equals(DataType.BUSSINESS)){
            Object result = response.getResult();
            ResponseCache.putResult(response.getRequestId(),result);
            log.info("放入返回结果缓存id{},内容{}",response.getRequestId(),result);
            //
            LouckCache.unLock(requestId);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss-SSS-XXX");
            IdleStateEvent event=(IdleStateEvent) evt;
            switch (event.state()){
                case WRITER_IDLE:
                    //发送心跳包
                    String s = format.format(new Date());
                    log.info("客户端通道没有写事件发生，主动发送心跳包时间【{}】",s);
                    new PangHeartBeatHandler().sendHeartBeat(ctx);
            }
        }
    }

}
